import {
    I18nOptions,
    createI18n,
} from 'vue-i18n'

import type {
    T_I18n_LocaleId,
    T_I18n_MessagesDict,
} from './types'



/**
 * Load locale messages
 *
 * The loaded `JSON` locale messages is pre-compiled by `@intlify/vue-i18n-loader`, which is integrated into `vue-cli-plugin-i18n`.
 * See: https://github.com/intlify/vue-i18n-loader#rocket-i18n-resource-pre-compilation
 */


function loadLocaleMessages () {
    const jsonModulesDict = import.meta.glob('./translations/*.json', { eager: true })
    const messagesDict = {} as T_I18n_MessagesDict
    Object.keys(jsonModulesDict).forEach(translationFileName => {
        const matched = translationFileName.match(/\/([A-Za-z0-9-_]+)\.js/i)
        if (matched && matched.length > 1) {
            const localeId = matched[1] as T_I18n_LocaleId
            const jsonModule = jsonModulesDict[translationFileName] as { default: Record<string, any>; }
            messagesDict[localeId] = jsonModule.default
        }
    })
    return messagesDict
}

const localLanguage = localStorage.getItem('xmeDataGatherI18n')

const i18nOptions: I18nOptions = {
    legacy: false,
    locale: localLanguage || import.meta.env.VITE_I18N_LOCALE || 'en',
    messages: loadLocaleMessages(),
    missingWarn: false,
    fallbackWarn: false,
}



export const i18n = createI18n(i18nOptions)

export * from './constants'
